<?php

namespace Music\ApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Music\ApiBundle\Lib\SimpleHtmlDom;
use Symfony\Component\HttpFoundation\Response;
use Music\ApiBundle\Entity\PlayList;
use Music\ApiBundle\Entity\ChangeVotes;
use Music\ApiBundle\Entity\LikeVotes;
use Music\ApiBundle\Entity\DeleteVotes;

class DefaultController extends Controller
{
    /**
     * @Route("/api/search/{query}")
     * @Template()
     */
    public function indexAction($query)
    {
        $query = str_replace(' ', '+', $query);
        return new Response(
            $this->get('namba.graber')->searchSong($query)->getResponse()
        );
    }

    /**
     * @Route("/api/stream/{id}")
     * @Template()
     */
    public function streamAction($id){
        $response  = $this->get('namba.graber')->loadStreamFile($id)->getResponse();
        $streamUrl = SimpleHtmlDom::getInstance($response)
                    ->find('div[class=startdownload]', 0)->children(2)->href;

        return new Response(
            $streamUrl
        );
    }
    
    /**
     * @Route("/api/playlist")
     * @Template()
     */
    public function playlistAction(){
        
        $playList = $this->get('doctrine.orm.entity_manager')
             ->createQueryBuilder('MusicApiBundle:PlayList')
             ->select('pl')
             ->from('MusicApiBundle:PlayList', 'pl')
             ->orderBy('pl.likes', 'DESC')
             ->getQuery()->getArrayResult();
        
        return new Response(
            json_encode($playList)
        );
    }
    
    /**
     * @Route("/api/playlist/add/{id}")
     * @Template()
     */
    public function playlistAddAction($id){

        if(!$this->getUser() OR !$this->getUser()->getAddBy()){
           return new Response(
                'error'
           );
        }
        
        $song = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:PlayList')->findOneBy(array('song_id' => $id));
        
        if($song){
           return new Response(
                'error'
           ); 
        }
        
        $response  = $this->get('namba.graber')->loadStreamFile($id)->getResponse();
        $response  = SimpleHtmlDom::getInstance($response)
                    ->find('p[class=u-filename]', 0)->innertext;
        
        $data = explode('<span>', $response);  
        $name = strip_tags(trim($data[0]));  
        
        $plsItem = new PlayList();
        $plsItem->setName($name);
        $plsItem->setSongId($id);
        $plsItem->setAddedBy($users[$_SERVER['REMOTE_ADDR']]);

        $this->get('doctrine.orm.entity_manager')->persist($plsItem);
        $this->get('doctrine.orm.entity_manager')->flush();
        
        return new Response(
            'success'
        );
    }
    
    /**
     * @Route("/api/played/{id}")
     * @Template()
     */
    public function playedAction($id){
        $this->get('doctrine.orm.entity_manager')
            ->createQueryBuilder()
            ->update('MusicApiBundle:PlayList', 'pl')
            ->set('pl.current_played', 0)
            ->getQuery()->getResult();

        $this->get('doctrine.orm.entity_manager')
            ->createQueryBuilder()
            ->update('MusicApiBundle:PlayList', 'pl')
            ->set('pl.current_played', 1)
            ->where('pl.song_id = :song_id')
            ->setParameter('song_id', $id)
            ->getQuery()->getResult();
        
        return new Response(
            'success'
        );
    }
    
    /**
     * @Route("/api/badvote/{id}")
     * @Template()
     */
    public function badVoteAction($id){
        $song = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:PlayList')->findOneBy(array('song_id' => $id));
        
        $song->setIgnoreCount($song->getIgnoreCount() + 1);
        
        $this->get('doctrine.orm.entity_manager')->persist($song);
        
        $vote = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:DeleteVotes')->findOneBy(array('song_id' => $id, 'user_id' => $this->getUser()->getId()));
        
        
        if($vote){
            return new Response(
                'error'
            );
        }
        
        $vote = new DeleteVotes();
        $vote->setSongId($id);
        $vote->setUserId($this->getUser()->getId());
        

        if($song->getIgnoreCount() == 6){
            $this->get('doctrine.orm.entity_manager')->remove($song);
            
            $playList = $this->get('doctrine.orm.entity_manager')
                 ->createQueryBuilder('MusicApiBundle:PlayList')
                 ->select('pl')
                 ->from('MusicApiBundle:PlayList', 'pl')
                 ->getQuery()->getArrayResult();

            foreach ($playList as $key => $item){
                if($item['song_id'] == $id){
                    if(isset($playList[$key-1])){
                        $prevId = $playList[$key-1]['id'];
                    } else {
                        $prevId = $playList[$key+1]['id'];
                    }
                    
                    $this->get('doctrine.orm.entity_manager')
                    ->createQueryBuilder()
                    ->update('MusicApiBundle:PlayList', 'pl')
                    ->set('pl.current_played', 0)
                    ->getQuery()->getResult();
                    
                    $prevSong = $this->get('doctrine.orm.entity_manager')
                        ->getRepository('MusicApiBundle:PlayList')->find($prevId);
                    $prevSong->setCurrentPlayed(1);
                    $this->get('doctrine.orm.entity_manager')->persist($prevSong);
                }
            } 
        }
        
        $this->get('doctrine.orm.entity_manager')->persist($vote); 
        $this->get('doctrine.orm.entity_manager')->flush();
        
        return new Response(
            'success'
        );
    }
    
    /**
     * @Route("/api/likevote/{id}")
     * @Template()
     */
    public function likeVoteAction($id){
        $song = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:PlayList')->findOneBy(array('song_id' => $id));
        
        $vote = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:LikeVotes')->findOneBy(array('song_id' => $id, 'user_id' => $this->getUser()->getId()));
        
        
        if($vote){
            return new Response(
                'error'
            );
        }
        
        $vote = new LikeVotes();
        $vote->setSongId($id);
        $vote->setUserId($this->getUser()->getId());
        
        $song->setLikes($song->getLikes() + 1);
        
        $this->get('doctrine.orm.entity_manager')->persist($vote); 
        $this->get('doctrine.orm.entity_manager')->persist($song);        
        $this->get('doctrine.orm.entity_manager')->flush();
        
        return new Response(
            'success'
        );
    }
    
    /**
     * @Route("/api/changevote/{id}")
     * @Template()
     */
    public function changeVoteAction($id){
        $song = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:PlayList')->findOneBy(array('song_id' => $id));
        
        $vote = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:ChangeVotes')->findOneBy(array('song_id' => $id, 'user_id' => $this->getUser()->getId()));
        
        
        if($vote){
            return new Response(
                'error'
            );
        }
        
        $vote = new ChangeVotes();
        $vote->setSongId($id);
        $vote->setUserId($this->getUser()->getId());
        
        $song->setChangeTrack($song->getChangeTrack() + 1);

        $this->get('doctrine.orm.entity_manager')->persist($song);   
        $this->get('doctrine.orm.entity_manager')->persist($vote); 
        $this->get('doctrine.orm.entity_manager')->flush();
        
        return new Response(
            'success'
        );
    }
    
    /**
     * @Route("/api/changed/{id}")
     * @Template()
     */
    public function changedAction($id){
        $song = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:PlayList')->findOneBy(array('song_id' => $id));
        
        $song->setChangeTrack(0);
        
        $votes = $this->get('doctrine.orm.entity_manager')
                ->getRepository('MusicApiBundle:ChangeVotes')->findBy(array('song_id' => $id));
        
        foreach($votes as $vote){
            $this->get('doctrine.orm.entity_manager')->remove($vote);
        }
        
        $this->get('doctrine.orm.entity_manager')->persist($song);        
        $this->get('doctrine.orm.entity_manager')->flush();
        
        return new Response(
            'success'
        );
    }
    
}
